package com.sessioncookie;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/DoFormServlet")
public class DoFormServlet extends HttpServlet {
	
	protected void doPost1(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html;charset=utf-8");// 防止浏览器显示乱码
		String userName = req.getParameter("userName");
		try {
			Thread.sleep(300);
		} catch (Exception e) {
			// TODO: handle exception
		}
		System.out.println("数据库插入数据...userName:" + userName);
		// 插入数据库...
		resp.getWriter().write("保存成功..");
		req.getSession().removeAttribute("sessionToken");
		
	}

	/****
	 * 使用后端的方式 来解决表单重复提交的问题
	 */
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html;charset=utf-8");// 防止浏览器显示乱码
        if(!isBumit(req)){
        	System.out.println("您提交提交了数据..或者token错误!");
        	resp.getWriter().write("您提交提交了数据..或者token错误!");
        	return ;
        }
		String userName = req.getParameter("userName");
		try {
			Thread.sleep(300);
		} catch (Exception e) {
			// TODO: handle exception
		}
		System.out.println("数据库插入数据...userName:" + userName);
		// 插入数据库...
		resp.getWriter().write("保存成功..");
		req.getSession().removeAttribute("sessionToken");
		
	}

	public Boolean isBumit(HttpServletRequest request) {
		String parameterToken = request.getParameter("parameterToken");
		String sessionToken = (String) request.getSession().getAttribute("sessionToken");
	    //判断是否提交
		if (sessionToken == null) {
			return false;
		}
		// 判断是否是伪造token
		if(!(parameterToken.equals(sessionToken))){
			return false;
		}
		return true;

	}

}
